package com.bwie.service.impl;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import com.bwie.service.WeChatPayService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * TODO
 *
 * @Description
 * @Author 36167
 * @Date 2025/3/11 19:25
 **/

@Service
public class WeChatPayServiceImpl implements WeChatPayService {


    public static String APP_ID = "wxab8acb865bb1637e";
    public static String APP_SECRET = "2ab9071b06b9f739b950ddb41db2690d";

    public static String MCH_ID = "11473623";
    public static String API_KEY = "2ab9071b06b9f739b950ddb41db2690d";

    @Override
    public String createSign(HashMap<String, String> hashMap) {
        //生成签名
        TreeMap<String, String> treeMap = new TreeMap<>(hashMap);
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> stringObjectEntry : treeMap.entrySet()) {
            if(stringObjectEntry.getValue() != null && !stringObjectEntry.getValue().isEmpty()){
                stringBuilder.append(stringObjectEntry.getKey()).append("=").append(stringObjectEntry.getValue()).append("&");
            }
        }
        String s = stringBuilder.toString();
        //加密
        String sign = DigestUtil.md5Hex(s + "key=" + API_KEY).toUpperCase();
        return sign;
    }

    @Override
    public String createPay(HashMap<String, String> hashMap) {
        //支付接口
        String urlApi = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String mapToXmlStr = XmlUtil.mapToXmlStr(hashMap,"xml");
        String contentType = HttpRequest.post(urlApi).header("Content-Type","application/xml")
                .body(mapToXmlStr).execute().body();
        System.out.println(contentType);
        Map<String, Object> map = XmlUtil.xmlToMap(contentType);
        String code = (String) map.get("code_url");
        return code;
    }
}
